package com.bestcem.xm.ticket.service.manager.record;

import cn.hutool.core.collection.CollUtil;
import com.bestcem.xm.ticket.entity.mongo.TicketRecord;
import com.bestcem.xm.ticket.entity.mongo.TicketTemplate;
import com.bestcem.xm.ticket.enums.TicketTemplateFieldNameEnum;
import com.bestcem.xm.ticket.enums.TicketTemplateFieldTypeEnum;
import com.bestcem.xm.ticket.service.manager.record.dto.FollowedCustomAttrDTO;
import com.bestcem.xm.ticket.service.manager.record.dto.TemplateFieldDTO;
import com.bestcem.xm.ticket.service.manager.record.param.FollowedTicketRecordParam;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;

/**
 * 工单进度记录 跟进 信息工具类
 *
 * @author XiaoYunSong <ys.xiao@idiaoyan.com>
 * @version v1.0
 * @date 2021/8/18 16:11
 */
@Slf4j
@ToString(callSuper = true)
@Getter
public final class FollowedTicketRecord extends BaseTicketRecord {
    /**
     * 是否完成跟进
     */
    private Boolean isCompleted;
    /**
     * 2.3版本修改为key是字段名称，value是字段的值
     * ---------------------------------------
     * 自定义字段列表
     * 如果字段是 {@link TicketTemplateFieldTypeEnum#TEXT}, 这里就是 String;     例: 'field1' => 'test'
     * 如果是 {@link TicketTemplateFieldTypeEnum#SELECT}, 这里就是int转的String; 例: 'field3' => '1'
     */
    private LinkedHashMap<String, String> fieldMap;
    /**
     * 工单规则模板
     */
    private Map<String, TemplateFieldDTO> template;

    private FollowedTicketRecord(FollowedTicketRecordParam param, TicketTemplate ticketTemplate) {
        super(param);
        if (Objects.nonNull(param)) {
            // 2.3版本后isCompleted 不再使用，该字段是用来控制跟进后审核用的
            if (param.getIsCompleted()) {
                this.isCompleted = false;
            } else {
                this.isCompleted = false;
            }
            this.fieldMap = new LinkedHashMap<>();
            LinkedHashMap<TicketTemplateFieldNameEnum, String> paramFieldMap = param.getFieldMap();
            if (!CollectionUtils.isEmpty(paramFieldMap)) {
                paramFieldMap.forEach((key, value) -> this.fieldMap.put(key.getName(), value));
            }
            if (CollUtil.isNotEmpty(param.getTemplateFields())) {
                param.getTemplateFields().forEach(o -> this.fieldMap.put(o.getName(), o.getAnswer()));
            }
        }
        this.template = new HashMap<>();
        if (Objects.nonNull(ticketTemplate)) {
            List<TicketTemplate.FieldInfo> customFields = ticketTemplate.getCustomFields();
            if (!CollectionUtils.isEmpty(customFields)) {
                this.template = parseTemplate(ticketTemplate);
            }
        }
    }

    /**
     * 构建实例
     *
     * @param param 入参
     * @return 实例
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/8/20 16:01
     */
    @Nullable
    public static FollowedTicketRecord getInstance(@Nonnull FollowedTicketRecordParam param, @Nonnull TicketTemplate ticketTemplate) {
        if (Objects.isNull(param)) {
            return null;
        }
        return new FollowedTicketRecord(param, ticketTemplate);
    }

    /**
     * 将 list 格式的custom_fields转化为 map 形式
     *
     * @param ticketTemplate 工单对应的 TicketTemplate 信息
     * @return map 形式的 custom_fields
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/8/18 21:08
     */
    @Nonnull
    private static Map<String, TemplateFieldDTO> parseTemplate(TicketTemplate ticketTemplate) {
        if (Objects.isNull(ticketTemplate)) {
            return new HashMap<>();
        }
        Map<String, TemplateFieldDTO> templateMap = new HashMap<>();
        List<TicketTemplate.FieldInfo> customFields = ticketTemplate.getCustomFields();
        // 转化工单中处理模板答案给工单日志
        if (!CollectionUtils.isEmpty(customFields)) {
            for (TicketTemplate.FieldInfo customField : customFields) {
                if (TicketTemplateFieldTypeEnum.TEXT.getName().equals(customField.getType())) {
                    templateMap.put(customField.getField(), TemplateFieldDTO.getTextInstance(customField));
                }
                if (TicketTemplateFieldTypeEnum.SELECT.getName().equals(customField.getType())) {
                    templateMap.put(customField.getField(), TemplateFieldDTO.getSelectInstance(customField));
                }
            }
        }

        return templateMap;
    }

    /***
     * 跟进 记录的自定义模板字段信息
     * @return 模板字段信息
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/8/19 15:38
     */
    @Nonnull
    @Override
    public TicketRecord.CustomAttr customAttr() {
        FollowedCustomAttrDTO followedCustomAttrDTO = new FollowedCustomAttrDTO();
        followedCustomAttrDTO.setContent(this.getContent());
        followedCustomAttrDTO.setIsCompleted(this.isCompleted);
        List<TicketRecord.CustomAttr.CustomField> customFields = new ArrayList<>();
        if (!CollectionUtils.isEmpty(this.fieldMap)) {
            this.fieldMap.forEach((field, value) -> {
                TicketRecord.CustomAttr.CustomField customField = this.renderField(field, value);
                if (Objects.nonNull(customField)) {
                    customFields.add(customField);
                }
            });
        }
        followedCustomAttrDTO.setCustomFields(customFields);
        return followedCustomAttrDTO.getCustomAttr();
    }

    /**
     * 将select题目中的字段value转换为option text
     *
     * @param fieldName 字段名
     * @param value     对应字段的值
     * @return 转换后的结果
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/8/19 15:24
     */
    @Nullable
    private TicketRecord.CustomAttr.CustomField renderField(String fieldName, String value) {
//        if (!this.template.containsKey(fieldName)) {
//            return null;
//        }
        TicketRecord.CustomAttr.CustomField customField = new TicketRecord.CustomAttr.CustomField();
//        TemplateFieldDTO templateFieldDTO = this.template.get(fieldName);
        customField.setText(fieldName);
        customField.setValue(value);
//        if (TicketTemplateFieldTypeEnum.TEXT.getName().equals(templateFieldDTO.getType())) {
//            customField.setValue(value);
//        }
//        if (TicketTemplateFieldTypeEnum.SELECT.getName().equals(templateFieldDTO.getType())) {
//            try {
//                Integer intValue = Integer.parseInt(value, 10);
//                String realValue = templateFieldDTO.getOptions().get(intValue);
//                if (ObjectUtils.isEmpty(realValue)) {
//                    log.error("[Ticket] 自定义字段值选项不存在; Field:{}; Value:{}; Template:{}; TicketId:{}",
//                            fieldName, value, this.template, this.getTicketId());
//                }
//                customField.setValue(realValue);
//            } catch (NumberFormatException e) {
//                log.error("[Ticket] 自定义字段值转int失败; Field:{}; Value:{}; TicketId:{}",
//                        fieldName, value, this.getTicketId(), e);
//                return null;
//            }
//        }
        return customField;
    }
}
